package com.controller;

import com.base.AjaxResult;
import com.base.BaseController;
import com.bean.WebsiteStatistics;
import com.bean.WebsiteUserInfo;
import com.bean.anno.LogAnno;
import com.mapper.mysql.UserInfoMapper;
import com.mapper.mysql.WebsiteStatisticsMapper;
import com.mapper.repository.mysql.UserInfoRepository;
import com.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@RestController
public class IndexController extends BaseController {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserInfoRepository userInfoRepository;


    @Autowired
    private JWTUtil jwtUtil;

    @LogAnno(apiName = "登录接口")
    @PostMapping("login")
    public AjaxResult login(@RequestBody WebsiteUserInfo userInfo,HttpServletResponse response){

        WebsiteUserInfo db = userInfoMapper.selectOne(userInfo);
        if(db != null){
            String token = jwtUtil.generateToken(db.getId());
            Cookie cookie = new Cookie("token",token);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return success("登录成功",token);
        }else{
            return error("用户名或密码错误");
        }
    }

    //私有的方法，影响依赖注入吗？  私有的方法依赖注入的内容为null,PostMapping能够注释private的方法
    @PostMapping("loginByType")
    public AjaxResult loginByType(@RequestBody WebsiteUserInfo userInfo,
                                   HttpServletRequest request,
                                   HttpServletResponse response) throws ServletException, IOException {
        System.out.println(userInfo.toString());
        System.out.println(userInfoMapper.toString());
        WebsiteUserInfo db = userInfoMapper.selectOne(userInfo);
        if(db != null){
            String token = jwtUtil.generateToken(db.getId());
            Cookie cookie = new Cookie("token",token);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            response.addCookie(cookie);

            if(userInfo.getType().equals("website")){
                //response.sendRedirect("backend_index.html");
                return success("登录成功","backend_websiteIndex.html");
            }
            if(userInfo.getType().equals("self")){
                //response.sendRedirect("logintoken.html");
                return success("登录成功","backend_selfLoginToken.html");
            }
            //request.getRequestDispatcher("backend_index.html").forward(request,response);//转发

            return success("登录成功");
        }else{
            return error("用户名或密码错误");
        }
    }


    @LogAnno(apiName = "退出登录")
    @PostMapping("loginOut")
    public AjaxResult loginOut(@RequestBody WebsiteUserInfo userInfo,HttpServletResponse response){
        Cookie cookie = new Cookie("token", "");
        // 设置与原有Cookie相同的路径和域名，确保覆盖生效
        cookie.setPath("/"); // 根路径，全网站可见
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return success("登录成功","backend_selfLogin.html");

    }

    @RequestMapping("/toLoginError")
    public AjaxResult toLoginError(@RequestParam("error")String error){

        return error(error,"/login");

    }


    //注册
    @PostMapping("register")
    public AjaxResult register(@Valid @RequestBody WebsiteUserInfo websiteUserInfo){
        int count = userInfoRepository.countByUsername(websiteUserInfo.getUsername());
        if(count>0){
            return error("用户名已存在，无法注册");
        }
        websiteUserInfo.setCreatetime(LocalDateTime.now());
        websiteUserInfo.setId(UUID.randomUUID().toString());
        userInfoRepository.save(websiteUserInfo);
        return success("注册成功，请登录");
    }


    @Autowired
    private WebsiteStatisticsMapper websiteStatisticsMapper;

    @GetMapping("statistics")
    public AjaxResult statistics(){

        WebsiteStatistics websiteStatistics = new WebsiteStatistics();
        websiteStatistics.setVisitCount(websiteStatisticsMapper.visitCount());
        websiteStatistics.setVisitors(websiteStatisticsMapper.visitors());
        websiteStatistics.setVisitUrlCount(websiteStatisticsMapper.visitUrlCount());
        websiteStatistics.setVisitorsUrl(websiteStatisticsMapper.visitorsUrl());

        return success("查询成功",websiteStatistics);
    }


}
